import { AxiosRequestConfig, AxiosResponse } from 'axios'
import { useAuthStore } from '../stores/auth.store'

export function authInterceptor() {
  const authStore = useAuthStore()

  // 请求拦截器
  const requestInterceptor = (config: AxiosRequestConfig) => {
    const token = authStore.getToken()
    
    if (token) {
      config.headers = config.headers || {}
      config.headers['Authorization'] = `Bearer ${token}`
    }
    
    return config
  }

  // 响应拦截器
  const responseInterceptor = (response: AxiosResponse) => {
    // 可以在这里处理特定的响应逻辑
    return response
  }

  // 错误拦截器
  const errorInterceptor = (error: any) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 未授权，清除用户信息并跳转到登录页
          authStore.logout()
          window.location.href = '/login'
          break
        case 403:
          // 权限不足
          console.error('Permission denied')
          break
        case 500:
          console.error('Server error')
          break
        default:
          console.error(`Error: ${error.response.status}`)
      }
    }
    
    return Promise.reject(error)
  }

  return {
    requestInterceptor,
    responseInterceptor,
    errorInterceptor
  }
}
